package com.xlh.security;

import com.xlh.constant.UserConstant;
import com.xlh.exception.ValidateCodeException;
import com.xlh.pojo.system.ImageCode;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 验证码拦截器
 * <p>
 * Created by lx on 2019/2/18.
 */
@Data
public class ValidateCodeFilter extends OncePerRequestFilter {

    private AuthenticationFailureHandler authenticationFailureHandler;

    private String pageUrl;

    private String httpMethod;

    public ValidateCodeFilter(String pageUrl, String httpMethod) {
        this.pageUrl = pageUrl;
        this.httpMethod = httpMethod;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        if (new AntPathRequestMatcher(pageUrl, httpMethod).matches(request)) {
            HttpSession session = request.getSession(true);
            Integer sessionFailNum = (Integer) session.getAttribute(UserConstant.CODE_FAIL_NUM);
            if (sessionFailNum != null && sessionFailNum > 0) {
                try {
                    validate((ImageCode) session.getAttribute(UserConstant.CODE_SESSION_KEY),
                            request.getParameter("code"));
                } catch (ValidateCodeException e) {
                    authenticationFailureHandler.onAuthenticationFailure(request, response, e);
                    return;
                }
            }
        }

        filterChain.doFilter(request, response);
    }

    private void validate(ImageCode sessionCode, String code) throws ServletRequestBindingException {

        if (sessionCode == null) return;

        if (StringUtils.isBlank(code)) {
            throw new ValidateCodeException("请输入验证码");
        }

        if (sessionCode.isExpired()) {
            throw new ValidateCodeException("图形验证码已失效，请重新获取");
        }

        if (!sessionCode.getCode().equalsIgnoreCase(code)) {
            throw new ValidateCodeException("验证码不正确");
        }

    }


}